package com.atguigu.msmService.controller;

import com.atguigu.commonUtils.Result;
import com.atguigu.commonUtils.ResultUtil;
import com.atguigu.msmService.service.MsmService;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Api(tags = "短信验证码校验")
@RestController
@RequestMapping("/msmService/msm")
@CrossOrigin
public class MsmController {

    @Resource
    private MsmService msmService;
    @Resource
    private RedisTemplate<String,String> redisTemplate;

    @GetMapping("/send/{phone}")
    public Result sendMsm(@PathVariable String phone){
        //先从redis中取验证码
        String code = redisTemplate.opsForValue().get(phone);

        if (!StringUtils.isEmpty(code)) {
            return ResultUtil.success();
        }
        code = Integer.toString((int)((Math.random()*9+1)*100000));
        Map<String, Object> map = new HashMap<>();
        map.put("code",code);

        Boolean isSend = msmService.sendMsm(map,phone);
        if (isSend) {
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return ResultUtil.success();
        }else {
            return ResultUtil.fail("短信验证码发送失败");
        }
    }

}
